using UnityEngine;
using WebSocketSharp;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Text;
using System;
using PimDeWitte.UnityMainThreadDispatcher;

public class GameController : MonoBehaviour
{
    private float rotationSpeed = 00.0f;
    private Color newColor = Color.red;

    public Transform cubeTransform;
    public Transform cube2Transform;
    public GameObject[] enemyPrefabs;
    public GameObject targetCube;
    public List<GameObject> enemies = new List<GameObject>();
    public WebSocket webSocket;

    private void Start()
    {
        DontDestroyOnLoad(gameObject);
        webSocket = new WebSocket("ws://192.168.43.1:8083/websocket");
        webSocket.OnMessage += OnWebSocketMessage;
        webSocket.Connect();
        Debug.Log("WebSocket connected to ws://192.168.43.1:8083/websocket");

        if (enemyPrefabs != null && enemyPrefabs.Length > 0 && cubeTransform != null && cube2Transform != null)
        {
            // Do additional initialization if needed
        }
        else
        {
            Debug.LogError("Check references in the Inspector.");
        }
    }

    void Update()
    {
        cubeTransform.Rotate(Vector3.up * rotationSpeed * Time.deltaTime);
        cube2Transform.Rotate(Vector3.up * rotationSpeed * Time.deltaTime);
    }

    private void OnWebSocketMessage(object sender, MessageEventArgs e)
    {
        string message = e.Data;
        string utf8Message = Encoding.UTF8.GetString(Encoding.Default.GetBytes(message));

        try
        {
            JObject jsonData = JObject.Parse(utf8Message);
            HandleUserAction(jsonData);
        }
        catch (JsonReaderException ex)
        {
            Debug.LogError("Error parsing JSON: " + ex.Message);
        }

        if (!webSocket.IsAlive)
        {
            Debug.LogWarning("WebSocket connection closed, reconnecting...");
            webSocket.Connect();
            Debug.Log("WebSocket reco ws://192.168.43.1:8083/websocket");
        }
    }

    private void HandleUserAction(JObject jsonData)
    {
        UnityMainThreadDispatcher.Instance().Enqueue(() =>
        {
            Debug.Log("HandleUserAction Lambda executed");

            try
            {
                Debug.Log("HandleUserAction started");

                if (jsonData["nickName"] != null)
                {
                    string username = jsonData["nickName"].ToString();
                    GameObject newEnemy = GenerateEnemy(username, jsonData);
                    enemies.Add(newEnemy);

                    Debug.Log("HandleUserAction: Player action processed successfully");
                }
                else
                {
                    Debug.LogError("Invalid user data in the message.");
                }

                Debug.Log("HandleUserAction completed");
            }
            catch (Exception ex)
            {
                Debug.LogError("HandleUserAction error: " + ex.Message);
            }
        });
    }

    private GameObject GenerateEnemy(string username, JObject jsonData)
    {
        if (targetCube != null && enemyPrefabs != null && enemyPrefabs.Length > 0)
        {
            Vector3 cubePosition = targetCube.transform.position;
            Vector2 randomOffset = UnityEngine.Random.insideUnitCircle * rotationSpeed;
            cubePosition += new Vector3(randomOffset.x, 0.0f, randomOffset.y);

            GameObject selectedPrefab = null;

            if (jsonData["giftName"] != null)
            {
                string giftName = jsonData["giftName"].ToString();

                // 根据不同礼物选择不同预制体
                switch (giftName)
                {
                    case "小心心":
                        selectedPrefab = enemyPrefabs[0]; // 假设小心心对应第一个预制体
                        break;

                    case "大啤酒":
                        selectedPrefab = enemyPrefabs[1]; // 假设大啤酒对应第二个预制体
                        break;

                    default:
                        Debug.LogError("Unhandled gift type: " + giftName);
                        return null;
                }
            }

            GameObject enemy = Instantiate(selectedPrefab, cubePosition, Quaternion.identity);
            Rigidbody enemyRigidbody = enemy.AddComponent<Rigidbody>();
            enemyRigidbody.freezeRotation = true;

            enemy.name = $"{selectedPrefab.name}_{username}";

            Debug.Log("Enemy generated at: " + cubePosition + ", Username: " + username);

            return enemy;
        }
        else
        {
            Debug.LogError("Check references in the Inspector.");
            return null;
        }
    }

    private void OnDestroy()
    {
        if (webSocket != null && webSocket.IsAlive)
        {
            webSocket.Close();
        }
    }
}
